Random Number Generation

What is random number?  and What is the use of it?

Random numbers: A sequence of numbers obtained by random sampling is  said to be random  numbers. Some of  its uses are
1.A tool for obtaining a random sample from actual finite population
As a source of manufactured data to use in studying sampling phenomena
3.As a tool to estimate the quantity which is not tractable with mathematics

A good reference is Ross, M (2006), Simulation, Elsevier

You can find several inbuilt command for generating random numbers from standard distributions. Using the command like rnorm(100), rnorm(100,2,10), runif(100) you can generate random numbers. Suppose we want to generate random numbers from triangular distribution, what we will do. There are several method to generate random numbers. Most popular among them are inverse transformation method. acceptance-rejection method, sums and mixture and transformation methods.

After understanding the concepts of inverse transformation method, please go through the following program so that it will save your time!

To generate a random sample of size 10000 from the distribution with density f(x)=3x^2, 0<x<1.
n=10000
u=runif(n)
x=u^(1/3) #(not that F(x)=x^3)
#to draw density histogram of sample
hist(x,prob=TRUE, main=expression(f(x)==3*x^2))

# to add density curve of f(x)
y=seq(0,1,.01)
lines(y,3*y^2)

To generate Bernoulli (p=.4)

#clearly F(0)=1-p and F(1)=1
# Thus F^-1(u)=1 if u>0.6 and F^-1(u)=0 if u<=0.6

n=10000
p=0.4
u=runif(n)
#to define (u>0.6 ) as logical vector
x=as.integer(u>0.6)
to find the mean and variance of the generated values
mean(x)
var(x)

# The following command will help you to generate Bernoulli random variable.
rbinom (n,size=1,prob=p)
sample(c(0,1),size=n,replace=TRUE,prob=c(.6,.4))

 

To generate geometric random variable
#f(x)=pq^x and F(x)=1-q^(x+1)
# we have to chose x which satisfies 1-q^(x)<u<=1-q^(x+1)
# it will simplifies to x<log(1-u)/log(q)<=x+1
#the solution is x+1=[log(1-u)/log(q)]

rgeometric=function(n,p){
u=runif(n)
geometric=numeric(n)
for(i in 1:n){
geometric[i]=ceiling(log(u[i])/log(1-p))-1             #Since the distribution of u and 1-u are same 
geometric
}

To Generate Poisson random variable
rpoisson <- function(n,lambda){
u <- runif(n)
vector <- length(n)
for(j in 1:n){
i <- 0
p <- exp(-lambda)
F <- p
while(u[j] >= F){
p <- lambda*p/(i+1)
F <- F+p
i<-i+1
}
vector[j] <- i
}
# output
vector
}

Note:  Like the Poisson case. one can write similar program for binomial random variable.

  

 back to notes